#!/bin/bash

MAIL_DIR=/home/liubin/mail/taisan_report/cur

function do_exist_files()
{
	for file in $MAIL_DIR/* ; do
		./fmt_taisan_report.sh $file
	done
}

function run_in_daemon()
{
	local piple=/tmp/.fmt_mail_in_taisan_report_of_lb
	if ! [ -p $piple ] ; then
		rm -rf $piple
		mkfifo $piple
	fi
	while read dir opt name ; do
		if ! [[ "$name" =~ ^msg\. ]] ; then
			continue
		fi
		sleep 3
		local file=$MAIL_DIR/$name
		if ! [ -f $file ] ; then
			file=$MAIL_DIR/${name}*
			if ! [ -f "$file" ] ; then 
				echo ERROR : $file NOT EXIST >&2
				continue
			fi
		fi
		./fmt_taisan_report.sh $file
	done < $piple >/dev/null 2>&1 &

	inotifywait -q -m -e create $MAIL_DIR >$piple 2>/dev/null </dev/null &
}


##################### BEGIN #######################
DO_EXIST=0
RUN_DAEMON=0
CHECK_FOR_UNDO=0

while getopts 'edc' opt ; do
	case "$opt" in
		e) DO_EXIST=1 ;;
		d) RUN_DAEMON=1 ;;
		c) CHECK_FOR_UNDO=1 ;;
		*) ;;
	esac
done

if ((CHECK_FOR_UNDO)) ; then
	echo CHECK_FOR_UNDO
	echo TODO
	exit 1
elif ((RUN_DAEMON)) ; then
	echo RUN_DAEMON
	run_in_daemon
elif ((DO_EXIST)) ; then
	echo DO_EXIST 
	do_exist_files
else
	echo "$(basename $0) [-e] [-d] [-c]"
	exit 1
fi
exit 0

